import {Component} from '@angular/core';
import {IonicPage, NavController} from 'ionic-angular';
import {LoginProvider} from "../../providers/login/login";
import {ToastController} from 'ionic-angular';

@IonicPage()
@Component({
    selector: 'page-login',
    templateUrl: 'login.html',
})
export class LoginPage {
    UTip: boolean = false; // 用户名验证提示
    PTip: boolean = false; // 密码验证提示
    uCont: string;  // 用户名
    pCont: string;  // 密码
    isDisabled: boolean;    // 禁用登录按钮

    constructor(public navCtrl: NavController,
                public loginProvider: LoginProvider,
                public toastCtrl: ToastController,) {
    }

    /**
     * 用户名验证是否为空
     * @param username
     */
    ckName(username) {
        if (username.value == 0) {
            this.UTip = true;
            this.uCont = "请输入用户名";
        } else {
            this.UTip = false;
        }
    }

    /**
     * 用户名获取焦点
     */
    namefocus() {
        this.UTip = false;
    }

    /**
     * 密码框获取焦点
     */
    pwdfocus() {
        this.PTip = false;
    }

    /**
     * / 密码验证
     * @param password
     */
    ckPwd(password) {
        if (password.value == 0) {
            this.PTip = true;
            this.pCont = "请输入密码";
        } else {
            this.PTip = false;
        }
    }

    /**
     * // 登录
     * @param {HTMLInputElement} username
     * @param {HTMLInputElement} password
     */
    logIn(username: HTMLInputElement, password: HTMLInputElement) {
        this.isDisabled = true;

        if (username.value.length == 0) {

            this.UTip = true;
            this.uCont = "请输入用户名";

        } else if (password.value.length == 0) {

            this.PTip = true;
            this.pCont = "请输入用密码";
        } else {

            this.PTip = false;
            this.UTip = false;

            this.loginProvider.doLogin({

                "UserName": username.value,
                "Password": password.value

            }).subscribe(res => {
                this.loginProvider.setLocalStorage(res);
                this.navCtrl.setRoot('TabsPage');
            }, err => {
                //todo 此处不关注失败的情况
                // this.loginFailed(err.error);
                //todo 这里不再使用err.json()
                // this.loginFailed(err.json());
            });
        }
        this.isDisabled = false;
    }

    /**
     * 登录失败 提示
     * @param err
     */
    // loginFailed(err) {
    //     this.toastCtrl.create({
    //         message: err.error_description,
    //         duration: 1200,
    //         position: 'bottom'
    //     }).present();
    // }
}
